package com.bizzard.basic.util;

import com.bizzard.basic.jwt.JwtUtils;
import com.bizzard.basic.jwt.LoginData;
import com.bizzard.basic.jwt.Payload;
import com.bizzard.basic.jwt.RsaUtils;
import com.bizzard.user.domain.Logininfo;


import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

public class LoginContext {

    /**
     * 获取当前登录人的登录信息
     * @param request
     * @return
     */
    public static Logininfo getLoginUser(HttpServletRequest request){
        //1.从请求头获取token - jwtToken
        String token = request.getHeader("token");
        if(token != null){
            //2.解密
            try {
                //2.1.获取公钥
                PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                //2.2.解密
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                //2.3.获取PayLoad - loginData - Logininfo
                return payload.getLoginData().getLogininfo();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}